package com.eportal.controller.background;

import com.alibaba.fastjson.JSONObject;
import com.eportal.action.background.TLocksAction;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TAgent;
import com.eportal.entity.TLocksDeliveylogEntity;
import com.eportal.entity.TLocksEntity;
import com.eportal.exception.MdKnownRunTimeException;
import com.eportal.params.background.TLocks.TLocksSendParam;
import com.eportal.params.background.TLocks.UpdateTlockParam;
import com.eportal.service.TAgentService;
import com.eportal.service.TLocksDeliveylogService;
import com.eportal.service.TLocksService;
import com.eportal.util.DateUtils;
import com.eportal.util.MdExpiringMap;
import com.eportal.util.WebUtil;
import com.eportal.vo.controller.background.tlocks.*;
import com.framework.jqgrid.Page;
import com.framework.jqgrid.PageEntity;
import com.github.pagehelper.PageInfo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;

/**
 * 硬件管理
 * @author chencheng
 *
 */
@Controller
@RequestMapping("/admin/tlocks")
public class TLocksController{


	private static Logger logger = LoggerFactory.getLogger(TLocksController.class.getName());

    @Resource
    private TLocksService tlocksService;

	@Resource
	private TLocksDeliveylogService tLocksDeliveylogService;

	@Resource
	private TAgentService tAgentService;

    /**
	 * 智能门禁管理列表
	 * @param param 		参数
	 * @param pageEntity 	分页
	 * @see TLocksAction#page()
	 * @author Saber
	 * @Date 2017/7/31 下午3:14
     */
	@RequestMapping(value = "page.json")
	@ResponseBody
    public JSONObject page(HttpServletRequest request,TLocksSendParam param,PageEntity pageEntity) throws Exception {

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
    	int userRole = (Integer)request.getSession().getAttribute("userRole");

		JSONObject json = new JSONObject();

		try {
			PageInfo<TlockListSendVO> pageInfo=tlocksService.queryForPage(pageEntity,param,user,userRole);

			json.put("total",pageInfo.getTotal());

			if(pageInfo.getList().size()==0){
				json.put("msg","暂无数据");
			}else{
				json.put("msg","ok");
			}
			json.put("data",pageInfo.getList());
			Page page = new Page(pageInfo,pageEntity.getPageNo());
			json.put("page", page);
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("门禁管理列表异常:",e);
			json.put("code", 0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
    }

	/**
	 * 智能门禁回收列表
	 * @author Saber
	 * @Date 2017/8/1 上午10:44
	 * @param pageEntity	分页对象
	 * @param pId1			pId开始
	 * @param pId2			pId截止
	 * @param type 			类型：0：一般合作方硬件，1：锁厂硬件
	 * @see TLocksAction#recoveryList()
	 * @return
	 */
	@RequestMapping(value = "recoveryList.json")
	@ResponseBody
	public JSONObject recoveryList(HttpServletRequest request,PageEntity pageEntity,String pId1,String pId2,String type){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			PageInfo<TlockRecoveryListVO> pageInfo=tlocksService.recoveryList(pageEntity, pId1,pId2,type, user, userRole);

			json.put("total",pageInfo.getTotal());

			if(pageInfo.getList().size()==0){
				json.put("msg","暂无数据");
			}else{
				json.put("msg","ok");
			}
			json.put("data",pageInfo.getList());
			Page page = new Page(pageInfo,pageEntity.getPageNo());
			json.put("page", page);
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取智能门禁发货列表异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}

	}

	/**
	 * 智能门禁回收
	 * @author Saber
	 * @Date 2017/8/1 下午2:26
	 * @param request
	 * @param pIds 		pids 集合
	 * @see TLocksAction#recovery()
	 * @return
	 */
	@RequestMapping(value = "recovery.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject recovery(HttpServletRequest request,String pIds){
		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json = tlocksService.recovery(pIds,user,userRole);
			return json;
		}catch (Exception e){
			json.put("code",0);
			json.put("msg","硬件回收失败");
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 智能门禁发货列表
	 * @param request
	 * @param pageEntity	分页对象
	 * @param pId1			pId开始
	 * @param pId2			pId截止
	 * @see TLocksAction#notSendList()
	 * @return
	 */
	@RequestMapping(value = "notSendList.json")
	@ResponseBody
	public JSONObject notSendList(HttpServletRequest request,PageEntity pageEntity,String pId1,String pId2){
		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			PageInfo<TLocksEntity> pageInfo=tlocksService.notSendList(pageEntity, pId1, pId2, user, userRole);

			json.put("total",pageInfo.getTotal());

			if(pageInfo.getList().size()==0){
				json.put("msg","暂无数据");
			}else{
				json.put("msg","ok");
			}
			json.put("data",pageInfo.getList());
			Page page = new Page(pageInfo,pageEntity.getPageNo());
			json.put("page", page);
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取智能门禁发货列表异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 智能门禁发货记录列表
	 * @author Saber
	 * @Date 2017/8/1 下午1:27
	 * @param request
	 * @param pageEntity		分页对象
	 * @param operationContent	操作内容
	 * @param operator			操作人
	 * @param sendTime 			操作时间
	 * @see TLocksAction#haveSendList()
	 * @return
	 */
	@RequestMapping(value = "haveSendList.json")
	@ResponseBody
	public JSONObject haveSendList(HttpServletRequest request,PageEntity pageEntity,String operationContent,String operator,String sendTime){
		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			PageInfo<TLocksDeliveylogEntity> pageInfo=tLocksDeliveylogService.haveSendList(pageEntity, operationContent, operator, sendTime, user, userRole);

			json.put("total",pageInfo.getTotal());

			if(pageInfo.getList().size()==0){
				json.put("msg","暂无数据");
			}else{
				json.put("msg","ok");
			}
			json.put("data",pageInfo.getList());
			Page page = new Page(pageInfo,pageEntity.getPageNo());
			json.put("page", page);
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取智能门禁发货记录列表异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 智能门禁安装列表（未安装的列表）
	 * @author Saber
	 * @Date 2017/8/1 下午4:38
	 * @param request
	 * @param pageEntity		分页对象
	 * @see TLocksAction#installTlocksList()
	 * @return
	 */
	@RequestMapping(value = "installTlocksList.json")
	@ResponseBody
	public JSONObject installTlocksList(HttpServletRequest request,PageEntity pageEntity){
		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			PageInfo<TLocksEntity> pageInfo=tlocksService.installTlocksList(pageEntity, user, userRole);

			json.put("total",pageInfo.getTotal());

			if(pageInfo.getList().size()==0){
				json.put("msg","暂无数据");
			}else{
				json.put("msg","ok");
			}
			json.put("data",pageInfo.getList());
			Page page = new Page(pageInfo,pageEntity.getPageNo());
			json.put("page", page);
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取智能门禁安装列表（未安装的列表）异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 智能门禁安装（根据sId安装）
	 * @author Saber
	 * @Date 2017/8/1 下午5:59
	 * @param request
	 * @param sId 		   		sId
	 * @param isPubunit 		门禁类型 0:私有门禁,1:公共门禁
	 * @param cBuildingId		楼栋id
	 * @param unitId 			单元id 对应于T032_CInstallUnit.SID 安装位置点编号在整个掌联系统中唯一编码
	 * @param lockName 			门禁名称
	 * @see   TLocksAction#installTlocks()
	 * @return
	 */
	@RequestMapping(value = "installTlocks.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject installTlocks(HttpServletRequest request,Long sId,String isPubunit,String cBuildingId,String unitId,String lockName){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json = tlocksService.installTlocks(request,sId,isPubunit,cBuildingId,unitId,lockName,user,userRole);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取智能门禁安装异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}


	/**
	 * 智能门禁安装（根据pId安装)）
	 * @author Saber
	 * @Date 2017/8/2 上午9:29
	 * @param request
	 * @param pId				pId
	 * @param checkCode			激活码
	 * @param isPubunit			门禁类型 0:私有门禁,1:公共门禁
	 * @param cBuildingId		楼栋id
	 * @param unitId	    	单元id
	 * @param lockName 			门禁名称
	 */
	@RequestMapping(value = "installTlocks2.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject installTlocks2(HttpServletRequest request,String pId,String checkCode,String isPubunit,String cBuildingId,String unitId,String lockName) {

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {

			//通过pId获取sId
			Long sId = tlocksService.validateLock(pId, checkCode);
			if (null == sId) {
				json.put("code", 0);
				json.put("msg", "没有匹配的硬件");
			} else {
				TAgent tAgent = tAgentService.get(Long.parseLong(user.getAgtCode()));
				Map map = tlocksService.changeTlockAgt(pId, tAgent.getAgtCode());// 执行发货操作
				if((Integer)map.get("code")==1){
					json = tlocksService.installTlocks(request,sId, isPubunit, cBuildingId, unitId, lockName, user.getCommunityId(), user.getAgtCode(), user);//todo Updated by Saber on 2017/7/27 上午11:02
				}else{
					logger.info("changeTlockAgt fail");
					json.put("code", 0);
					json.put("msg", "安装硬件失败");
				}
			}
		} catch (MdKnownRunTimeException e) {
			e.printStackTrace();
			json.put("code", 0);
			json.put("msg", e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			json.put("code", 0);
			json.put("msg", "安装硬件失败");
			logger.error("安装硬件失败:", e);
		}
		return json;
	}

	/**
	 * 智能门禁安装记录列表
	 * @author Saber
	 * @Date 2017/8/3 下午2:19
	 * @param request
	 * @param pageEntity
	 * @param pageEntity		分页对象
	 * @param operationContent	操作内容
	 * @param operator			操作人
	 * @param sendTime 			操作时间
	 * @see TLocksAction#installLogList()
	 * @return
	 */
	@RequestMapping(value = "installLogList.json")
	@ResponseBody
	public JSONObject installLogList(HttpServletRequest request,PageEntity pageEntity,String operationContent,String operator,String sendTime){
		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			PageInfo<TLocksInstalllogListVO> pageInfo=tlocksService.installLogList(pageEntity, user, userRole,operationContent,operator,sendTime);

			json.put("total",pageInfo.getTotal());

			if(pageInfo.getList().size()==0){
				json.put("msg","暂无数据");
			}else{
				json.put("msg","ok");
			}
			json.put("data",pageInfo.getList());
			Page page = new Page(pageInfo,pageEntity.getPageNo());
			json.put("page", page);
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取智能门禁安装列表（未安装的列表）异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 门禁列表
	 * @author Saber
	 * @Date 2017/8/10 下午2:29
	 * @param request
	 * @param type 			钥匙类型: private :私有钥匙  share:共有钥匙
	 * @param communityId 	小区id
	 * @see TLocksAction#tlockList
	 * @return
	 */
	@RequestMapping(value = "tlockList.json")
	@ResponseBody
	public JSONObject tlockList(HttpServletRequest request,String type,String communityId){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			List<TlockListVO> list=tlocksService.tlockList(type, communityId, user, userRole);

			if(list.size()==0){
				json.put("msg","暂无数据");
			}else{
				json.put("msg","ok");
			}
			json.put("data",list);
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("获取智门禁列表异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 安装点修改详情
	 * @author Saber
	 * @Date 2017/8/11 上午9:10
	 * @param request
	 * @param sId		sId
	 * @see TLocksAction#editInstallView()
	 * @return
	 */
	@RequestMapping(value = "getInstallDetail.json")
	@ResponseBody
	public JSONObject getInstallDetail(HttpServletRequest request,Long sId){

		JSONObject json = new JSONObject();

		try {
			InstallTlockDetailVO detail=tlocksService.getInstallTlockDetail(sId);

			json.put("data",detail);
			json.put("msg","ok");
			json.put("code",1);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("安装点修改详情异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 门禁修改
	 * @author Saber
	 * @Date 2017/8/11 下午12:01
	 * @param request
	 * @param param 	参数
	 * @see TLocksAction#update()
	 * @return
	 */
	@RequestMapping(value = "update.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject update(HttpServletRequest request,UpdateTlockParam param){
		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json=tlocksService.update(request,param,user,userRole);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("安装点修改异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 智能门禁更换
	 * @author Saber
	 * @Date 2017/8/11 下午2:15
	 * @param request
	 * @param sId			sId
	 * @param newPid		新门禁pId
	 * @param checkCode 	激活码
	 * @return
	 */
	@RequestMapping(value = "saveChange.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject saveChange(HttpServletRequest request,Long sId,String newPid,String checkCode){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json=tlocksService.saveChange(sId, newPid, checkCode, user, userRole);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("智能门禁更换详情异常:",e);
			json.put("code",0);
			json.put("msg","服务器发生异常:"+e.getMessage());
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 智能门禁发货
	 * @author Saber
	 * @Date 2017/8/16 上午11:37
	 * @param request
	 * @param agtCode		合作方				agtCode或communityId其中一个不能为空
	 * @param communityId 	小区id
	 * @param sIds 			sId集合 用,分割		非空
	 * @see TLocksAction#sendToTagent()
	 * @return
	 */
	@RequestMapping(value = "sendToTagent.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject sendToTagent(HttpServletRequest request,String agtCode,String communityId,String sIds){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json = tlocksService.sendToAgent(agtCode,communityId,sIds,user,userRole);//todo Updated by Saber on 2017/7/27 上午11:33
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("智能门禁发货异常", e);
			json.put("code", "0");
			json.put("msg", "操作失败");
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 智能门禁批量发货
	 * @author Saber
	 * @Date 2017/8/16 下午1:32
	 * @param request
	 * @param agtCode			合作方				agtCode或communityId其中一个不能为空
	 * @param communityId		小区id
	 * @param pIdBegin			pId初始值
	 * @param pIdEnd			pId结束值
	 * @see TLocksAction#sendToBatchTagent()
	 * @return
	 */
	@RequestMapping(value = "sendToBatchTagent.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject sendToBatchTagent(HttpServletRequest request,String agtCode,String communityId,String pIdBegin,String pIdEnd){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json = tlocksService.sendToBatchTagent(agtCode,communityId,pIdBegin,pIdEnd,user,userRole);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("智能门禁批量发货异常", e);
			json.put("code", "0");
			json.put("msg", "操作失败");
			json.put("data",null);
			return json;
		}
	}


	/**
	 * 硬件检测（是否合格）【该方法其实其实就是合格和不合格的接口】
	 * @author Saber
	 * @Date 2017/8/21 下午1:00
	 * @param request
	 * @param ids		sId集合 用,分割
	 * @param type 		检验状态,0:未检测，1：检查通过，2检查不通过
	 * @see TLocksAction#check()
	 * @return
	 */
	@RequestMapping(value = "check.json")
	@ResponseBody
	public JSONObject check(HttpServletRequest request,String ids,String type){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json = tlocksService.check(ids,type,user,userRole);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("硬件检测异常", e);
			json.put("code", "0");
			json.put("msg", "操作失败");
			json.put("data",null);
			return json;
		}
	}

	/**
	 * 硬件新增保存
	 * //todo 该接口仅管理端后台使用、app无法使用,如想改成app也可用,请修改代码
	 * @author Saber
	 * @Date 2017/8/21 下午1:50
	 * @param request
	 * @param pId 					PID
	 * @param checkCode 			激活码
	 * @param installLockName 		门禁名称
	 * @see TLocksAction#add()
	 * @return
	 */
	@RequestMapping(value = "add.json",method = RequestMethod.POST)
	@ResponseBody
	public JSONObject add(HttpServletRequest request,String pId,String checkCode,String installLockName,String type){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole = (Integer)request.getSession().getAttribute("userRole");

		try {
			json = tlocksService.add(pId, checkCode,installLockName, user, userRole);
			return json;
		}catch (Exception e){
			e.printStackTrace();
			logger.error("硬件检测异常", e);
			json.put("code", "0");
			json.put("msg", "操作失败");
			json.put("data",null);
			return json;
		}
	}

	private static MdExpiringMap<String, HSSFWorkbook> fileMap = new MdExpiringMap<String, HSSFWorkbook>(240, 10);
	/**
	 * 导出激活码（生成数据excel）
	 * @author Saber
	 * @Date 2017/8/21 下午4:11
	 * @param request
	 * @param pIdBegin	pId初始值
	 * @param pIdEnd	pId结束值
	 * @see TLocksAction#export()
	 * @return
	 */
	@RequestMapping(value = "export.json")
	@ResponseBody
	public JSONObject export(HttpServletRequest request,String pIdBegin,String pIdEnd){

		JSONObject json = new JSONObject();

		Sysopt user= (Sysopt)request.getSession().getAttribute("user");
		int userRole =  (Integer)request.getSession().getAttribute("userRole");

		try{
			String[] titles = {"pid","激活码","二维码内容","二维码图片"};
			if(pIdBegin==null||pIdBegin.length()<1){
				json.put("code", 0);
				json.put("msg", "初始pid必填");
				return json;
			}
			if(pIdEnd==null||pIdEnd.length()<1){
				json.put("code", 0);
				json.put("msg", "结束pid必填");
				return json;
			}
			pIdBegin = pIdBegin.replaceAll(" ", "");
			pIdEnd = pIdEnd.replaceAll(" ", "");
			List<TLocksEntity> list =tlocksService.getByPidAndAgtCodeForExport(pIdBegin, pIdEnd, user, userRole);
			String fileid = UUID.randomUUID().toString();
			//fileMap.put(fileid, ExcelUtil.export("硬件数据", dataList));//考虑到激活码等敏感信息，将文件放在内存中，长时间没下载，或者下载一次后清除。


			final int qrcodeWidth=280;//二维码的宽度
			HSSFWorkbook wb = new HSSFWorkbook();
			HSSFSheet sheet1 = wb.createSheet("device");
			sheet1.setColumnWidth(3, Double.valueOf(qrcodeWidth*35.7).intValue());//宽度 n像素
			sheet1.setColumnWidth(2, Double.valueOf(300*35.7).intValue());
			sheet1.setColumnWidth(1, Double.valueOf(200*35.7).intValue());
			sheet1.setColumnWidth(0, Double.valueOf(200*35.7).intValue());
			HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
			Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//编码
			hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);//容错率
			hints.put(EncodeHintType.MARGIN, 0);
			for(int i=0;i<list.size();i++){
				TLocksEntity lock = list.get(i);
				String url = WebUtil.getReqPreUrl(request) + "a?p=" + lock.getPid() + "&c=" + lock.getCheckcode()
						+ "&v=1";
				BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeWidth, hints);
				BufferedImage bufferImg = toBufferedImage(bitMatrix);
				ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
				ImageIO.write(bufferImg, "jpg", byteArrayOut);

				//画图的顶级管理器，一个sheet只能获取一个（一定要注意这点）

				//anchor主要用于设置图片的属性
				HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0,(short) 3, i+1, (short) 4, i+2);
				//anchor.setAnchorType(3);
				//插入图片
				patriarch.createPicture(anchor, wb.addPicture(byteArrayOut.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));
				HSSFRow row1 = sheet1.createRow(i+1);
				row1.setHeight((short) (qrcodeWidth*15.625)); //高度 n像素
				row1.createCell(0).setCellValue(lock.getPid());
				row1.createCell(1).setCellValue(lock.getCheckcode());

				row1.createCell(2).setCellValue(url);
			}

			HSSFRow row1 = sheet1.createRow(0);
			for(int j=0;j<titles.length;j++){
				row1.createCell(j).setCellValue(titles[j]);
			}
			fileMap.put(fileid, wb);

			json.put("code", 1);
			json.put("msg", "操作成功");
			json.put("url", request.getContextPath()+"/admin/tlocks/getFile.json?id="+fileid);//todo 与原码不同 使用新的地址
			return json;
		}catch(Exception e){
			logger.error("", e);
			json.put("code", 0);
			json.put("msg", "导出数据繁忙");
			return json;
		}
	}


	private static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}
	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;

	/**
	 * 导出激活码（生成数据excel）获取文件
	 * @author Saber
	 * @Date 2017/8/21 下午4:57
	 * @param request
	 * @param id 			文件id
	 * @see TLocksAction#getFile()
	 * @return
	 */
	@RequestMapping(value = "getFile.json")
	@ResponseBody
	public JSONObject getFile(HttpServletRequest request,HttpServletResponse response,String id) {

		JSONObject json = new JSONObject();

		try{

			HSSFWorkbook workbook = fileMap.get(id);
			if(workbook!=null){

				response.addHeader("Content-Disposition", "attachment;filename=" + new String("device_" + DateUtils.formatDatetime(new Date(), "yyyy_MM_dd_HHmmss") + ".xls"));
				//getResponse().setContentType("application/octet-stream");
				response.setContentType("multipart/form-data");
				workbook.write(response.getOutputStream());
				response.getOutputStream().flush();
				response.getOutputStream().close();
				workbook=null;//清除文件

				json.put("code",1);
				json.put("msg","导出成功");
				json.put("data",null);
				return json;
			}
			json.put("code",0);
			json.put("msg","获取文件超时,请重新导出");
			json.put("data",null);
			return json;
		}catch(Exception e){
			logger.error("获取文件异常",e);
			e.printStackTrace();
			json.put("code",0);
			json.put("msg","获取文件异常");
			json.put("data",null);
			return json;
		}
	}

}
